<?php

namespace app\admin\controller\wechat;

use app\admin\controller\general\Profile;
use app\common\controller\Backend;
use think\Exception;

/**
 * 药品管理
 *
 * @icon fa fa-circle-o
 */
class Articles extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wechat\Articles;
        $this->modelAccount = new \app\admin\model\wechat\Accounts;
        $this->modelDraft = new \app\admin\model\wechat\Drafts;
        $this->modelGather = new \app\admin\model\wechat\Gather;
        $this->access_token = $this->modelAccount->getAccessToken();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            print_r($offset);
            $list = $this->model
                ->where($where)
                ->where("state <2 AND uid = " . $this->auth->id)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
//            echo $this->model->getlastsql();

//            $lists = $this->model->order('id DESC')->select();
            foreach ($lists as $k => $v) {
                $gatherInfo = $this->modelGather->where("id = '" . $v['gather_id'] . "'")->find();
                $lists[$k]['gather'] = $gatherInfo;
                if ($v['state'] !== 0) {
                    // $info=   $this->modelDraft->where("FIND_IN_SET('" . $v['id'] . "',articles_ids)")->find();
                    $firstInfo = $this->modelDraft->where("articles_ids like '" . $v['id'] . "%'")->find();

                    $lists[$k]['is_first'] = $firstInfo ? 1 : 0;
                }
            }
            $total = count($lists);
            $result = array("total" => $total, "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {

        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $detail = $this->model->where("id =" . $ids)->find()->toArray();
            if ($detail['state'] === 2) {
                $this->error('已发布的不能修改');
            }

            $post = input("post.");
            $data = $post['row'];

            // 先删除草稿，再生成新的草稿

            // 1、若是内容和封面没有改，则不做图片处理？？
            // 2、那得先删除之前草稿的图片
            // 2.1 先合并封面图片，然后全部删除

            $data['cover'] = $data['cover'] ? $data['cover'] : $this->getEditorFirstImg($data['content']);
            if ($detail['state'] == 1 && !$data['cover']) {
                $this->error('封面和编辑器都没有图片');
            }

            $this->model->where("id =" . $ids)->update($data);

            // 编辑公众号草稿
            if ($detail['state'] === 1) {
                $draft_id = $detail['draft_id'];

                $draft_detail = $this->modelDraft->where("id =" . $draft_id)->find()->toArray();

                // 先删除草稿，再重新生成
                $deleteDraftResult = $this->modelDraft->deleteDraft($this->access_token, $draft_detail['media_id']);

                if ($deleteDraftResult['errmsg'] === 'ok' && $draft_detail['articles_ids']) {
                    // 更新所有文章为待发布
                    $this->model->where("id IN (" . $draft_detail['articles_ids'] . ")")->update(array('state' => 0));
                    $this->makeDraft($draft_detail['articles_ids']);

                }
            }


            $this->success('ok');
            return;
        }
        $row = $this->model->where("id =" . $ids)->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function makeDraft($ids = null)
    {
        $ids = input('post.ids') ? input('post.ids') : $ids;
        $idsNew = array();
        $lists = collection($this->model->where("id IN (" . $ids . ")")->order('weigh DESC,id DESC')->select())->toArray();
        foreach ($lists as $v) {
            if ($v['state'] !== 0) {
                $this->error('id：' . $v['id'] . '状态不是待发布');
                exit;
            }
            $idsNew[] = $v['id'];
        }

        if (count($lists) === 0) {
            $this->error('没有待发布的草稿');
        }

        $media = $this->getMediaStr($lists);
        $url_material = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token=" . $this->access_token; //调用该接口需https协议
        $curl_info = curl_post($url_material, 'post', $media);


        $arr = json_decode($curl_info, true);
        if (!isset($arr['media_id'])) {
            $this->error($arr['errmsg']);
            exit;
        }
        // 生成草稿
        $draft = array();
        $draft['aid'] = 1;
        $draft['articles_ids'] = implode(',', $idsNew);
        $draft['state'] = 1;
        $draft['media_id'] = $arr['media_id'];
        $draft['addtime'] = date('Y-m-d H:i:s');
        $draft['updatetime'] = date('Y-m-d H:i:s');

        $lastId = $this->modelDraft->insertGetId($draft);
        if ($lastId) {
            $this->model->where("id IN (" . $ids . ")")->update(array('state' => 1, 'draft_id' => $lastId));
            $this->success('生成草稿成功');
        } else {
            $this->error('本地添加草稿失败');
        }
    }

    public function getContentImgs($content)
    {
        $content = htmlspecialchars_decode($content);

        $pattern_img = "/<img.*?src=[\\\'| \\\"](.*?)[\\\'|\\\"].*?[\/]?>/";
        preg_match_all($pattern_img, $content, $imagesMatch1);
        $imagesArr1 = $imagesMatch1[1];
        $regex = '/url\(\'{0,1}\"{0,1}(.*?)\'{0,1}\"{0,1}\)/';
        preg_match_all($regex, $content, $imagesMatch2);
        $imagesArr2 = $imagesMatch2[1];
        if ($imagesArr1 && $imagesArr2) {
            $merge = array_merge($imagesArr1, $imagesArr2);
        } else {
            $merge = $imagesArr1 ? $imagesArr1 : $imagesArr2;
        }
        foreach ($merge as $v) {
            $img_news = $this->getCurlImg($v); //生成本服务器相对路径图片
            $img_weixin = $this->getInnerPic($img_news); //相对路径图片转换微信消息图片
            $content = str_replace($v, $img_weixin, $content); //内容中的图片地址转换成微信消息图片地址
        }


        $content_new = str_replace("\"", "'", $content); //双引号转换单引号
        return $content_new;
    }

    public function getCurlImg($pic_url)
    {
        $put_name = $this->getNewFileName($pic_url);

        $file_get = file_get_contents($pic_url);


        file_put_contents($put_name, $file_get);
        return $put_name;
    }

    public function getInnerPic($img)
    { //图文消息素材

        $url_material = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" . $this->access_token; //调用该接口需https协议
        $parsedUrl = parse_url($img);
//    echo $img."<hr>";
        $media = array("media" => "@./" . $parsedUrl['path']);
        // print_r($media);

        $curl_upload = curl_post($url_material, 'post', $media);
        $arr = json_decode($curl_upload, true);
        return $arr['url'];
    }

    private function getPicForever($img)
    { //新增永久素材
        if (!$img) {
            $this->error('getPicForever：图片不存在');
        }
        $url_material = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" . $this->access_token . "&type=image"; //调用该接口需https协议

//        $parsedUrl = parse_url($img); // ?

        // 该图片不存在
//        $put_name = $this->getNewFileName($img);

        $put_name = $this->getCurlImg($img);

        $media = array("media" => "@./" . $put_name);
//        print_r($media);

        $curl_upload = curl_post($url_material, 'post', $media);
        $arr = json_decode($curl_upload, true);

        if (!isset($arr['media_id'])) {
            $this->error('getPicForever：' . $arr['errmsg']);
        }
        return $arr['media_id'];
    }

    private function getEditorFirstImg($content)
    {
        $pattern_img = "/<img.*?src=[\\\'| \\\"](.*?(?:[\.gif|\.jpg]))[\\\'|\\\"].*?[\/]?>/";
        preg_match_all($pattern_img, $content, $imagesMatch1);

        $imagesArr1 = $imagesMatch1[1];

        $first = "";

        foreach ($imagesArr1 as $v) {
            $imgInfo = getimagesize($v);
            $height = $imgInfo[1];
            if ($height > 200) {
                $first = $v;
                break;
            }
        }
        if (!$first) {
            $first = isset($imagesArr1[0]) ? $imagesArr1[0] : '';
        }
        return $first;
    }

    private function getMediaStr($lists)
    {

        $media = '{"articles": [';
        foreach ($lists as $v) {
            $content_weixin = $this->getContentImgs($v['content']);

            // 封面
            $cover_id = $v['cover'] ? $this->getPicForever($v['cover']) : $this->getEditorFirstImg($content_weixin);

            $media .= '{
     "title": "' . $v['title'] . '",
    "thumb_media_id": "' . $cover_id . '",
    "author": "' . $v['author'] . '",
    "digest": "' . $v['summary'] . '",
    "show_cover_pic": 1,
    "content": "' . $content_weixin . '",
    "content_source_url": "' . $v['source_url'] . '",
    "need_open_comment":"0"
},';
        }
        $media .= ']}';
        return $media;
    }

    public function makeContent()
    {
        $str = `<section style="display: flex;justify-content: space-between;align-items: center;border-radius: 10px;overflow-wrap: break-word !important;box-sizing: border-box;"><section data-width="100%" style="max-width: 100% !important;box-sizing:border-box;width: 100%;border-radius: 10px;overflow-wrap: break-word !important;"><img class="rich_pages wxw-img" data-backh="403" data-backw="186" data-cropselx1="0" data-cropselx2="186" data-cropsely1="0" data-cropsely2="402" data-ratio="2.164814814814815" data-src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49wVGSfc1nZ9l1n3IA3GEsr3ibLY9WHm2Lax2q47YILUuDj425GOo2fuqA/640?wx_fmt=jpeg&amp;from=appmsg" data-type="jpeg" data-w="1080" style="box-sizing: border-box; vertical-align: inherit; border-radius: 10px; width: 219px !important; height: auto !important; overflow-wrap: break-word !important; max-width: 100% !important; visibility: visible !important;" data-original-style="box-sizing: border-box;vertical-align: inherit;border-radius: 10px;width: 100%;height: auto;overflow-wrap: break-word !important;max-width: 100% !important;" data-index="8" src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49wVGSfc1nZ9l1n3IA3GEsr3ibLY9WHm2Lax2q47YILUuDj425GOo2fuqA/640?wx_fmt=jpeg&amp;from=appmsg&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1" _width="100%" crossorigin="anonymous" alt="图片" data-fail="0"></section><section data-width="100%" style="max-width: 100% !important;box-sizing:border-box;margin-right: 10px;margin-left: 10px;width: 100%;border-radius: 10px;overflow-wrap: break-word !important;"><img class="rich_pages wxw-img" data-backh="403" data-backw="186" data-cropselx1="0" data-cropselx2="186" data-cropsely1="1" data-cropsely2="401" data-ratio="2.1675925925925927" data-src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49wQrFr7Ym1LOsOOtoiaKIxrIJIy8hZiclEFvZv7MJpqPdJa8rBjSeUteew/640?wx_fmt=jpeg&amp;from=appmsg" data-type="jpeg" data-w="1080" style="vertical-align: inherit; color: rgb(62, 62, 62); font-family: &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 16px; text-align: start; white-space: normal; box-sizing: border-box; border-radius: 10px; width: 219px !important; height: auto !important; overflow-wrap: break-word !important; visibility: visible !important;" data-original-style="vertical-align: inherit;color: rgb(62, 62, 62);font-family: &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif;font-size: 16px;text-align: start;white-space: normal;box-sizing: border-box;border-radius: 10px;width: 100%;height: auto;overflow-wrap: break-word !important;" data-index="9" src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49wQrFr7Ym1LOsOOtoiaKIxrIJIy8hZiclEFvZv7MJpqPdJa8rBjSeUteew/640?wx_fmt=jpeg&amp;from=appmsg&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1" _width="100%" crossorigin="anonymous" alt="图片" data-fail="0"></section><section data-width="100%" style="max-width: 100% !important;box-sizing:border-box;width: 100%;border-radius: 10px;overflow-wrap: break-word !important;"><img class="rich_pages wxw-img" data-backh="402" data-backw="186" data-cropselx1="0" data-cropselx2="186" data-cropsely1="0" data-cropsely2="402" data-ratio="2.162037037037037" data-src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49w0A90r8MBCNKNtvicSe89YDPibOiaQbZWutoq1LSibticJspAiauFoWkIMbKA/640?wx_fmt=jpeg&amp;from=appmsg" data-type="jpeg" data-w="1080" style="box-sizing: border-box; vertical-align: inherit; border-radius: 10px; width: 219px !important; height: auto !important; overflow-wrap: break-word !important; max-width: 100% !important; visibility: visible !important;" data-original-style="box-sizing: border-box;vertical-align: inherit;border-radius: 10px;width: 100%;height: auto;overflow-wrap: break-word !important;max-width: 100% !important;" data-index="10" src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/FCIGOSXGF3L8fAdp8LVAjgX7ruAXP49w0A90r8MBCNKNtvicSe89YDPibOiaQbZWutoq1LSibticJspAiauFoWkIMbKA/640?wx_fmt=jpeg&amp;from=appmsg&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1" _width="100%" crossorigin="anonymous" alt="图片" data-fail="0"><span style="letter-spacing: 0.544px;color: rgb(255, 172, 170);font-family: 微软雅黑;font-size: 12px;widows: 1;background-color: rgb(255, 255, 255);text-align: center;"></span><span style="letter-spacing: 0.544px;color: rgb(255, 172, 170);font-family: 微软雅黑;font-size: 12px;widows: 1;background-color: rgb(255, 255, 255);text-align: center;"></span></section></section>`;
        return $str;
    }

    private function getExtension($pic_url)
    {
        $pattern = '/mmbiz_(.+?)\//is';

        $extension = "";
        if (preg_match($pattern, $pic_url, $matches)) {
            $extension = $matches[1];
        }

        if (!$extension) {
            $this->error("未匹配到图片类型" . $pic_url);
        }
        return $extension;
    }

    private function getNewFileName($pic_url)
    {
        $dir = 'mpweixintemp/';
        if (!file_exists($dir)) {
            mkdir($dir);
        }

        $extension = $this->getExtension($pic_url);
        $put_name = $dir . date("YmdHis") . rand(1000, 9999) . "." . $extension;
        return $put_name;
    }

    //http://www.guoman-admin.com/panel.php/wechat/articles/test
    public function test()
    {
        $str = "猫咪壁纸，温暖你的情感世界。女孩倩影，点缀你的视线；风景如画，引领你走进自然之美；男孩阳光，照亮你心灵的角落；花开绽放，为你的生活增添一抹色彩。这些元素，如同生活中的点滴，汇聚成一幅幅精美的画卷，让你的心灵在美好的事物中畅游。";
        $strs = explode('。',$str);
        $arr = array();
        foreach($strs as $v){
            $strs2 = explode('；',$v);

            foreach($strs2 as $k2=>$v2){
                $v2trim = trim($v2);
                if($k2 === 0){
                    $fuhao = "。";
                }
                if($v2trim){

                    $arr[] = $v2.$fuhao;
                }

            }
        }
      print_r($arr);
//        $v= "https://mmbiz.qpic.cn/sz_mmbiz_png/0ZUPFs8FEgu3hx7rakmSc3tEcfZPAVrK23CxicDrbTKMQS8dXv5iaYe9OmngZAo4oQEnt04CobcUeb8cc2iaRormQ/640?wx_fmt=png";
//        $imgInfo = getimagesize($v);
//        $height = $imgInfo[1];
//        print_r($imgInfo);
//        $content = $this->model->getCopyWriting();
//        print_r($content);
        exit;

        $content = "<section style='display: flex; justify-content: space-between; align-items: center; border-radius: 10px; box-sizing: border-box; overflow-wrap: break-word !important; visibility: visible;'></section>";
        $content = htmlspecialchars_decode($content);

        $pattern_img = "/<img.*?src=[\\\'| \\\"](.*?)[\\\'|\\\"].*?[\/]?>/";
        preg_match_all($pattern_img, $content, $imagesMatch1);

        $imagesArr1 = $imagesMatch1[1];
        $regex = '/url\(\'{0,1}\"{0,1}(.*?)\'{0,1}\"{0,1}\)/';
        preg_match_all($regex, $content, $imagesMatch2);
        $imagesArr2 = $imagesMatch2[1];

        if ($imagesArr1 && $imagesArr2) {
            $merge = array_merge($imagesArr1, $imagesArr2);
        } else {
            $merge = $imagesArr1 ? $imagesArr1 : $imagesArr2;
        }
        foreach ($merge as $v) {
            $img_news = $this->getCurlImg($v); //生成本服务器相对路径图片
            $img_weixin = $this->getInnerPic($img_news); //相对路径图片转换微信消息图片
            $content = str_replace($v, $img_weixin, $content); //内容中的图片地址转换成微信消息图片地址
        }


        $content_new = str_replace("\"", "'", $content); //双引号转换单引号
        echo $content_new;
    }

    //http://www.guoman-admin.com/panel.php/wechat/articles/modal  https://mp.weixin.qq.com/s/EvdBFr-agi3KAjiALUXpOQ
    public function modal()
    {

        $id = input('post.id');
        $type = input('post.type');
        $info = $this->model->where("id = '" . $id . "'")->find();
        $imgs = explode(',', $info['imgs']);



        $lists = [];
        $copyrightings = $this->splitCopyrighting($info['copyrighting']);
//    print_r($copyrightings);
        if($type == 2){

            $lists  = $this->getTwoLists($imgs,$copyrightings);
        }else{
            $lists = $imgs;
        }


        $this->view->assign("lists", $lists);
        return $this->view->fetch('modal' . $type);
    }
// https://mp.weixin.qq.com/s?__biz=MzU0MDE1MTQ4Nw==&mid=2247623285&idx=1&sn=4bf9cdb882d81c7126637e09e863f63c&chksm=fb3139a5cc46b0b37df803755182f477df2c266687459dd50264b524814d0486f62dcf772986&scene=27
    private function getTwoLists($imgs,$copyrightings){
        $imgs_total = count($imgs);
        $img_items = 2;
        $length = ceil($imgs_total / $img_items);
        $length_copyrightings = count($copyrightings);

        $length_item = ceil($length_copyrightings / $length);

        for ($i = 0; $i < $length; $i++) {
            $itemImg = [];
            for ($j = 0; $j < $img_items; $j++) {
                if ($i * $img_items + $j < $imgs_total && $imgs[$i * $img_items + $j]) {

                    array_push($itemImg, $imgs[$i * $img_items + $j]);
                }
            }
            $lists[$i]['imgs'] = $itemImg;
            $lists[$i]['tips'] = [];
            for ($z = 0; $z < $length_item; $z++) {

                    if(isset($copyrightings[$i*$length_item+$z])){

                        array_push($lists[$i]['tips'], $copyrightings[$i*$length_item+$z]);
                    }else{
                        array_push($lists[$i]['tips'], $this->model->getCopyWriting());
                    }

            }
          //   $lists[$i]['tip'] = $this->model->getCopyWriting();
            $lists[$i]['split']  = '';
           // $lists[$i]['split'] = '<img src="https://mmbiz.qpic.cn/mmbiz_gif/FLJyibqft5NX5eqic7xzKWwvdXCmLLwd4avPPZI2OaZeQlCTXpZLia08xUlFxtE2UFhskicZMHiaTLkgx3o0fQhsd4g/0?wx_fmt=gif&from=appmsg"/>';

        }
//     print_r($lists);exit;

        return $lists;
    }

    private function splitCopyrighting($str){
        if(!$str){
            return [];
        }
        $strs = explode('。',$str);
        $arr = array();
        foreach($strs as $v){
            $strs2 = explode('；',$v);

            foreach($strs2 as $k2=>$v2){
                $v2trim = trim($v2);
                if($k2 === 0){
                    $fuhao = "。";
                }
                if($v2trim){

                    $arr[] = $v2.$fuhao;
                }

            }
        }
        return $arr;
    }
}
